package wx

import (
    "github.com/gin-gonic/gin"
    "github.com/silenceper/wechat/v2"
    "github.com/silenceper/wechat/v2/cache"
    "github.com/silenceper/wechat/v2/miniprogram"
    miniConfig "github.com/silenceper/wechat/v2/miniprogram/config"
    "go.uber.org/zap"
    "iip/webserver"
)

type WX struct {
    cfg    *Config
    l      *zap.Logger
    logger *zap.SugaredLogger
    websrv *webserver.WebServer
    mini   *miniprogram.MiniProgram
}

func New() *WX {
    x := &WX{}
    return x
}

func (s *WX) WithLogger(l *zap.Logger) *WX {
    s.l = l.With(zap.String("mod", "account"))
    s.logger = s.l.Sugar()
    return s
}

func (s *WX) WithConfig(cfg *Config) *WX {
    s.cfg = cfg
    return s
}

func (s *WX) WithWebServer(srv *webserver.WebServer) *WX {
    s.websrv = srv
    return s
}

func (s *WX) Start() {
    wc := wechat.NewWechat()
    memory := cache.NewMemory()

    cfg := &miniConfig.Config{
        AppID:     s.cfg.AppID,
        AppSecret: s.cfg.Secret,
        Cache:     memory,
    }
    // s.logger.Info(s.cfg.AppID)
    // s.logger.Info(s.cfg.Secret)
    s.mini = wc.GetMiniProgram(cfg)

    s.websrv.GinEngine().GET("/wxmini/request", s.OnWXRequest)
    s.websrv.GinEngine().POST("/wxmini/request", s.OnWXRequest)
}

// ?code=091F2EFa1XpU7A0wW4Ga1OE5ga0F2EFc
func (s *WX) OnWXRequest(c *gin.Context) {
    code := c.Query("code")
    if code == "" {
        s.logger.Error("no code")
        return
    }
    auth := s.mini.GetAuth()
    ret, err := auth.Code2Session(code)
    if err != nil {
        s.logger.Error(err.Error())
        return
    }
    openid := ret.OpenID
    unionid := ret.UnionID
    session_key := ret.SessionKey
    errcode := ret.ErrCode
    errmsg := ret.ErrMsg

    // s.logger.Info(openid)
    // s.logger.Info(unionid)
    // s.logger.Info(session_key)
    // s.logger.Info(errcode)
    // s.logger.Info(errmsg)

    c.JSON(200, gin.H{
        "openid":      openid,
        "unionid":     unionid,
        "session_key": session_key,
        "errcode":     errcode,
        "errmsg":      errmsg,
    })
}
